package cgroup

import (
	"JudgeSandBox/common"
	"JudgeSandBox/utils"
	"fmt"
	"os"
	"path"
	"strconv"
)

type Cpu struct {
	subsystem
	uuid string
	path string
}

func GetCpu(uuid string) *Cpu {
	sprintf := fmt.Sprintf(common.CgroupCpuPath, uuid)
	if err := os.MkdirAll(sprintf, 0755); err != nil {
		utils.PrintToLog("Error creating Cpu object:", err)
		return nil
	}
	return &Cpu{
		uuid: uuid,
		path: sprintf,
	}
}

// Set Set("10000","100000") //默认进程最多占用单个cpu 10%的算力
func (c Cpu) Set(quota, period string) error {
	if err := os.WriteFile(path.Join(c.path, common.CpuCfsQuotaUs), []byte(quota), 0755); err != nil {
		return err
	}
	if err := os.WriteFile(path.Join(c.path, common.CpuCfsPeriodUs), []byte(period), 0755); err != nil {
		return err
	}
	return nil
}

func (c Cpu) Put(pid int) error {
	if err := os.WriteFile(path.Join(c.path, common.Tasks), []byte(strconv.Itoa(pid)), 0755); err != nil {
		return err
	}
	return nil
}

func (c Cpu) Remove() error {
	return os.RemoveAll(c.path)
}
